class WxRequest {
  defaults = {
    // baseURL: 'https://security.dfteco.com', // 注意
    baseURL: "http://192.168.2.202:8888",
    url: "", // 接口的请求路径
    data: null,
    method: "GET",
    header: {
      "Content-type": "application/json", // 设置数据的交互格式
    },
    timeout: 60000, // 默认的超时时长，小程序默认的超时时长是 1 分钟
    isLoading: true, // 控制是否使用默认的 loading，默认值是 true 表示使用默认的 loading
  };

  interceptors = {
    request: (config) => {
      //请求拦截
      const token = wx.getStorageSync("token");
      const tenant = wx.getStorageSync("tenantCode");
      if (token) {
        config.header["X-token"] = `${token}`;
        config.header["tenant"] = `${tenant}`;
      }
      return config;
    },
    response: (response) => {
      //响应拦截
      let { data } = response;
      switch (data.code) {
        case 0:
          return data;
        case 1:
          wx.showToast({
            title: data.message || "未知错误",
            icon: "error",
            duration: 2000,
          });
          return Promise.reject(response);
        case 10404:
          wx.showToast({
            title: "当前微信号暂未绑定\r\n请使用账号密码登录",
            icon: "none",
            duration: 2000,
          });
          setTimeout(() => {
            wx.navigateTo({
              url: "/pages/login/box/box",
            });
          }, 3000);
          return;
        default:
          return Promise.reject(response);
      }
    },
  };

  queue = [];

  constructor(params = {}) {
    this.defaults = Object.assign({}, this.defaults, params);
  }

  request(options) {
    this.timerId && clearTimeout(this.timerId);
    options.url = this.defaults.baseURL + options.url;
    options = {
      ...this.defaults,
      ...options,
    };
    if (options.isLoading && options.method !== "UPLOAD") {
      this.queue.length === 0 && wx.showLoading();
      this.queue.push("request");
    }
    options = this.interceptors.request(options);
    return new Promise((resolve, reject) => {
      if (options.method === "UPLOAD") {
        wx.uploadFile({
          ...options,
          success: (res) => {
            res.data = JSON.parse(res.data);
            const mergeRes = Object.assign({}, res, {
              config: options,
              isSuccess: true,
            });
            resolve(this.interceptors.response(mergeRes));
          },
          fail: (err) => {
            const mergeErr = Object.assign({}, err, {
              config: options,
              isSuccess: false,
            });
            reject(this.interceptors.response(mergeErr));
          },
        });
      } else {
        wx.request({
          ...options,
          success: (res) => {
            const mergeRes = Object.assign({}, res, {
              config: options,
              isSuccess: true,
            });
            resolve(this.interceptors.response(mergeRes));
          },
          fail: (err) => {
            const mergeErr = Object.assign({}, err, {
              config: options,
              isSuccess: false,
            });
            reject(this.interceptors.response(mergeErr));
          },
          complete: () => {
            if (options.isLoading) {
              this.queue.pop();
              this.queue.length === 0 && this.queue.push("request");
              this.timerId = setTimeout(() => {
                this.queue.pop();
                this.queue.length === 0 && wx.hideLoading();
                clearTimeout(this.timerId);
              }, 200);
            }
          },
        });
      }
    });
  }
  get(url, data = {}, config = {}) {
    return this.request(
      Object.assign(
        {
          url,
          data,
          method: "GET",
        },
        config
      )
    );
  }

  delete(url, data = {}, config = {}) {
    return this.request(
      Object.assign(
        {
          url,
          data,
          method: "DELETE",
        },
        config
      )
    );
  }

  post(url, data = {}, config = {}) {
    return this.request(
      Object.assign(
        {
          url,
          data,
          method: "POST",
        },
        config
      )
    );
  }

  put(url, data = {}, config = {}) {
    return this.request(
      Object.assign(
        {
          url,
          data,
          method: "PUT",
        },
        config
      )
    );
  }

  all(...promise) {
    return Promise.all(promise);
  }

  upload(url, filePath, name = "file", config = {}) {
    return this.request(
      Object.assign(
        {
          url,
          filePath,
          name,
          method: "UPLOAD",
        },
        config
      )
    );
  }
}
const http = new WxRequest();
export default http;
